# 主要目标
# 1. 找出所有涨停的记录
# 2. 分析其后的第1天，第2天，。。。，第7天的单日涨幅
# 3. 分析其后的第1天，第2天，。。。，第7天的累计涨幅
# 日志
# 2025/01/15 新建本脚本，并初步实现基本功能。
# 2025/01/26 更新脚本，使输出更合理。
# 2025/02/07 根据新数据更新脚本，并对sz.002016进行验证

import os, sys
from datetime import datetime, timedelta
import pandas as pd
from utils.common import *
print('功能说明: 统计指定股票在封板后，第n天相对涨停价的上涨次数。\n')
print('函数定义:\n    python ./zhangting_anlyzer.py stock_code[ days=5]\n')
print('    stock_code     股票代码，要以sh.或sz.开头, 如sz.000430')
print('    days           统计的天数，默认值为5，要以sh.或sz.开头, 如sz.000430\n')
print('使用示例:\n    python ./zhangting_anlyzer.py sz.000430 10\n')


stock_code = 'sz.002016'
if len(sys.argv) > 1:
    stock_code = sys.argv[1]
day_count = int(sys.argv[2]) if len(sys.argv) > 2 else 5

# 0=date   1=preclose  2=open  3=high   4=low   5=close
#  date      code  open  high   low  close  preclose      volume       amount  adjustflag      turn  tradestatus  pctChg  isST 
# 2024-11-23 ['sz.002016', 10.98, 10.98, 10.98, 10.98, 9.98, 5424586.0, 59561954.0, 3, 0.839595, 1, 10.02, 0]

df = pd.read_csv(f'./daily_data/{stock_code}.csv')
res = []
ups1 = 0
for id, row in df.iterrows():
    data = row.tolist()
    high = data[3]
    close = data[5]
    preclose = data[6]
    # 根据最高价与昨日收盘价的比值判断是否有涨停，只要是涨停就添加，不考虑封板情况。
    if abs(preclose * 1.1 - high) < 0.01:
        ups1 = ups1 + 1
        if abs(high - close) < 0.01:
            res.append((id, data)) # 只保存封停的数据

#  date      code  open  high   low  close  preclose      volume       amount  adjustflag      turn  tradestatus  pctChg  isST 
# 2024-11-23 ['sz.002016', 10.98, 10.98, 10.98, 10.98, 9.98, 5424586.0, 59561954.0, 3, 0.839595, 1, 10.02, 0]
counter = 0
id = 0
up_times = { }
benefits = { }
for i in range(day_count):
    up_times[i] = 0
    benefits[i] = 0

for row_id, data in res:
    row = df.loc[row_id].tolist()
    code = row[0]
    close = row[5]
    preclose = row[6]   # 初始的收盘价
    high1 = row[3]      # 第1天的涨停价，后续是否上涨，就参考这个值。
    #print(row)
    id = id + 1
    print(f'{id:2}   {code} {preclose:6.2f} -> {high1:6.2f}   ', end='')
    for i in range(day_count):
        if row_id + i + 1 >= len(df):
            break
        high = df['high'].iloc[row_id + i + 1]          # 当天最高价
        benefits[i] = benefits[i] + (high - high1)
        mark = '    '  # 只要上涨的就显示 ↑↑
        if high > high1:                # 统计第1列的上涨次数
           mark = ' ↑↑ '
           up_times[i] = up_times[i] + 1
        rate = high / preclose - 1
        print(f' {high:6.2f}({rate:7.2%}){mark}',  end="")
    print()

record_count = len(res)
print(f'{stock_code} 共涨停 {ups1} 次数, 封板 {record_count} ')
for key in up_times:
    t1 = up_times[key]
    up_rate = 1.0 * up_times[key] / record_count
    benefit = benefits[key]/record_count
    print(f'    封板后 day {key+1:<2}, 上涨次数 {t1:2}/{record_count} ({up_rate:5.1%}), 收益: {benefit:6.2f}.')
#if len(res) > 0:
#else:
#    print('len(res) = 0')